<?php

namespace StudyBuddy\Controllers;

use \StudyBuddy\String;

class Changepwd extends Resetpwd
{
	const TPL_SUCCESS = 'Password updated successfully';

	protected $membersOnly = true;
	
	protected $aRequired = array();
	
	protected $layoutID = 1;

	/**
	 * @var object of type Form
	 */
	protected $oForm;



	/**
	 * New password
	 *
	 * @var string
	 */
	protected $newPwd;


	protected function main(){

		$this->oForm = new \StudyBuddy\Forms\Changepwd($this->oRegistry);
		$this->oForm->formTitle = $this->aPageVars['title'] = $this->_('Change Password');

		if($this->oForm->isSubmitted() && $this->oForm->validate()){
			$this->saveNewPassword();
			if(!empty($this->email)){
				$this->emailPwd();
			}

			$this->aPageVars['body'] = '<div id="tools">'.$this->_('Password updated successfully').'</div>';

		} else {
			$this->aPageVars['body'] = $this->oForm->getForm();
		}
	}


	/**
	 * Update ['pwd'] in Viewer object and save object
	 *
	 * @return object $this
	 */
	protected function saveNewPassword(){
		$this->email = $this->oRegistry->Viewer['email'];
		$this->username = $this->oRegistry->Viewer['username'];
		$this->newPwd = $this->oRequest['pwd1'];

		$this->oRegistry->Viewer['pwd'] = String::hashPassword($this->newPwd);
		$this->oRegistry->Viewer->save();

		return $this;
	}
}
